#!/usr/bin/env coffee

axios=  require 'axios'
cheerio = require('cheerio')
sleep = require "@6du/sleep"
jsonfile = require "jsonfile"
path = require "path"
fs = require 'fs-extra'
CITY = require './city.js'
axiosCookieJar = require('axios-cookiejar-support').default
tough = require('tough-cookie')
minify = require('html-minifier').minify

do =>
  keyword = "唯品会"

  ax = axios.create({
    baseURL: "https://www.dianping.com/"
  })
  axiosCookieJar(ax)
  ax.defaults.jar = new tough.CookieJar()
  ax.defaults.headers["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
  r = await ax.get("beijing")
  console.log r.headers
  console.log ax.defaults.jar
  await sleep 3

  for city_id in CITY.ID
    page = 1
    {data} = await ax.get("search/keyword/#{city_id}/0_#{encodeURIComponent(keyword)}/o11p#{page}")
    console.log data
    if data.indexOf('class="not-found-words"') < 0
      html = minify(data, {
        removeAttributeQuotes: true
      })
      console.log html
    break
  #  #

  # {data} = await axios.get("https://www.dianping.com/citylist")
  # city = new Set()
  # file = path.join(__dirname, 'city.json')
  # cityId = await jsonfile.readFile file

  # $ = cheerio.load(data)
  # en_cn = {}

  # for i in $('.onecity')
  #   i = $(i)
  #   en = i.attr('href').split("/").pop()
  #   city.add en
  #   en_cn[en] = i.text().trim()

  # for i,n in Array.from city
  #   if i of cityId
  #     continue
  #   {data} = await axios.get("https://www.dianping.com/#{i}")
  #   id = extract data , "'cityId'", ','
  #   id = id.match(/\d+/)[0] - 0
  #   cityId[i] = id
  #   await jsonfile.writeFile(file, cityId)
  #   console.log (1+n), i, id

  # li = []

  # for k,v of cityId
  #   li.push [v,k]

  # li.sort (a,b)=>a-b

  # cn_li =[]
  # id_li = []
  # for [id,city] in li
  #   cn_li.push en_cn[city]
  #   id_li.push id

  # js = """
# const CITY_CN=#{JSON.stringify(cn_li)},CITY_ID=#{JSON.stringify(id_li)};"""
  # await fs.writeFile(path.join(__dirname, "../city.js"), js)
